import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Table, Pagination, Message, Dialog, Button, Balloon, Loading, Dropdown, Menu, Upload, Grid, Icon, Tag } from '@alifd/next';
import IceContainer from '@icedesign/container';
import IconSvg from '#/components/IconSvg';
import TableFilter from './TableFilter';
import EditForm from './EditForm';
import { ApiOfResourcePage, ApiOfResourceEnable, ApiOfResourceDisable, ApiOfResourceDelete, ApiOfResourceExport } from '#/utils/coreApiDefine'
import { ApiOfResourceImport, ApiOfResourceTemplate } from '#/utils/coreApiDefine'
import SearchTableWrapper from '#/hoc/SearchTableWrapper'
import moment from 'moment'

const { Row, Col } = Grid;
@SearchTableWrapper(ApiOfResourcePage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      loading: false,
      detailDialogVisible: false,
      editInstance: {},
      rowSelection: {
        onChange: this.onRowSelectChange.bind(this),
        selectedRows: [],
      },
    };
  }

  renderGatewayDesc = (value, index, item) => {
    let that = this;
    if (!item.gateway || !item.gateway.config) {
      return (
        <div></div>
      );
    } else {
      let desc = item.gateway.name + '(' + item.gateway.physicalConnType + ')'
      let gatewayConfig = JSON.parse(item.gateway.config);
      return (
        <div>
          <Balloon
            trigger={
              <Link to = {"/manage/lowermachine/" + item.gateway.code + '/operation'}>{desc}</Link>
            }
            align="r"
            closable={false}
            triggerType="hover">

            {Object.keys(gatewayConfig).map(function (k) {
              return (
                <dl style={that.props.styles.horizontal.dl} key={k}>
                  <dt style={that.props.styles.horizontal.dt}>{k}:</dt>
                  <dd style={that.props.styles.horizontal.dd}>{gatewayConfig[k]}</dd>
                </dl>
              );
            })}

          </Balloon>
        </div>
      );
    }
  }

  renderMetricGroup = (value, index, item) => {
    let that = this;
    if (item.metricGroupSize == 0) {
      return (
        <div></div>
      );
    } else {
      return (
        <div>
          {item.metricGroups.map(function (k, i) {
            return (
              <div key={i}>{k.name}({k.usageType == 'COLLECT' ? '采集' : '控制'})</div>
            );
          })}
        </div>
      );
    }
  }

  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    let that = this;
    const linkProps = {
      to: "/manage/device/" + item.code + "/bindmetricgroups"
    };

    const linkToOperationPage = {
      to: "/manage/device/" + item.code + "/operation"
    };

    const statusIcon = (item) => {
      let iconClass = "#icon-yunhang";
      if (!item.disabled) {
        iconClass = "#icon-tingzhi";
      }
      return iconClass;
    }

    const startStop = <Button title={item.disabled ? '启用' : '停用'} onClick={() => this.onToggleStatusConfirm(item)} type="primary" text>
      <IconSvg iconClass={statusIcon(item)} style={{ width: '1.2em', height: '1.2em' }} />
    </Button>

    const edit = <Button title="编辑" onClick={() => this.onOpenDetailDialog(item)} type="primary" text style={{ marginLeft: '5px' }}>
      <IconSvg iconClass="#icon-bianji" style={{ width: '1.2em', height: '1.2em' }} />
    </Button>

    const metricGroup = <Link title="指标组" {...linkProps} style={{ marginLeft: '5px' }}>
      <IconSvg iconClass="#icon-fenzuguanli" style={{ width: '1.2em', height: '1.2em' }} />
    </Link>

    const operation = <Link title="管理" {...linkToOperationPage} style={{ marginLeft: '5px' }}>
      <IconSvg iconClass="#icon-guanli" style={{ width: '1.2em', height: '1.2em' }} />
    </Link>

    const remove = <Button title="删除" onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text style={{ marginLeft: '5px' }}>
      <IconSvg iconClass="#icon-shanchu" style={{ width: '1.2em', height: '1.2em' }} />
    </Button>

    return (

      <div>
        {startStop}
        {edit}
        {metricGroup}
        {operation}
        {remove}
      </div>
    );
  }

  renderStatus = (value, index, item) => {
    return (
      <Tag type="primary" color={item.disabled ? 'red' : 'green'} size="small">{item.disabled ? '已停用' : '已启动'}</Tag>
    );
  }

  renderConfig = (value, index, item) => {
    let that = this;
    if (!item.config) {
      return (
        <div></div>
      );
    } else {
      let config = JSON.parse(item.config);
      return (
        <div>
          {Object.keys(config).map(function (k) {
            return (
              <dl style={that.props.styles.horizontal.dl} key={k}>
                <dt style={that.props.styles.horizontal.dt}>{k}</dt>
                <dd style={that.props.styles.horizontal.dd}>{config[k]}</dd>
              </dl>
            );
          })}
        </div>
      );
    }
  }

  renderExecutionCycle = (value, index, item) => {
    let dur = item.executionCycle;
    if(item.executionCycle > 60) {
      dur = moment.duration(item.executionCycle, 'seconds').asMinutes() + ' 分'
    } else {
      dur = moment.duration(item.executionCycle, 'seconds').asSeconds() + ' 秒'
    }
    return (
      <span>{dur}</span>
    );
  }
  
  // 选择模式时，选择项改变事件
  onRowSelectChange(ids, records) {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    rowSelection.selectedRows = [...rowSelection.selectedRows, ...records];
    this.setState({ rowSelection });
  }

  // 选择模式时，选择好后的确认事件
  onSelectConfirm() {
    let possibleRows = this.state.rowSelection.selectedRows,
      selectedRowKeys = this.state.rowSelection.selectedRowKeys;
    let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1);
    this.props.onSelect(selectedRows)
  }

  onDeleteConfirmOk = item => {
    return ApiOfResourceDelete(item.code)
  }

  onToggleStatusConfirm = (item) => {
    let that = this;
    let Api = item.disabled ? ApiOfResourceEnable : ApiOfResourceDisable
    Dialog.confirm({
      title: '',
      content: '确认要' + (item.disabled ? '开启' : '禁用') + '吗?',
      onOk: () => {
        Api(item.code).then(response => {
          that.props.fetch();
          Message.success('操作成功!');
        }).catch(function (error) {
          console.log(error);
        });
      }
    });
  }

  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }

  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  renderName = (value, index, item) => {
    const linkProps = {
      to: "/manage/device/" + item.code + '/operation'
    };
    return (
      <Link {...linkProps}>{item.name}</Link>
    );
  }

  beforeUpload = (info) => {
    if (info.size > 5242880) {
      Message.error('上传文件过大,超过5M；文件名：' + info.name);
      return false;
    }
    var ss = info.name.substr(info.name.lastIndexOf(".")).toLowerCase();
    if (ss != '.xlsx') {
      Message.error('文件格式不支持,请选择.xlsx的文件；文件名：' + info.name);
      return false;
    }
    Message.loading('上传文件中,请等待；文件名：' + info.name);
  }
  onSuccess = (info) => {
    var status = info.response.status;
    // console.log(info);
    if ('success' === status) {
      this.props.fetch();
      Message.show({
        type: 'success',
        title: '资源导入',
        duration: 5000,
        content: '导入成功：' + info.name
      });
    } else if ('failure' === status) {
      Message.show({
        type: 'error',
        title: '资源导入',
        duration: 10000,
        content: '导入失败，错误原因：' + info.response.errors[0].errmsg
      });
      this.props.fetch();
      return false;
    }
  }
  onError = (info) => {
    Message.error('导入失败，错误原因：' + info.response.errors[0].errmsg);
    return false;
  }
  exportData() {
    var that = this;
    var serarch = that.props.search;
    var url = ApiOfResourceExport + '?';
    Object.keys(serarch).forEach(key => {
      if (serarch[key] != null) {
        url = url + key + '=' + serarch[key] + '&';
      }
    });
    fetch(url).then(res => res.blob().then(blob => {
      let a = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      let filename = res.headers.get('Content-disposition');
      if (filename) {
        filename = decodeURI(filename.split('=')[1]); //提取文件名
        a.href = url;
        a.download = filename; //给下载下来的文件起个名字
        a.click();
        window.URL.revokeObjectURL(url);
        a = null;
      }
    }));
  }
  render() {
    const { instances } = this.props.bindingData;
    let DisplayTable;
    let ActionBar;
    if (this.props.forSelectUsage === true) {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            primaryKey="id"
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
            rowSelection={this.state.rowSelection}
          >
            <Table.Column width={200} title="名称" dataIndex="name" sortable={true} />
            <Table.Column width={140} title="编码" dataIndex="code" />
            <Table.Column
              width={160}
              title="网关"
              sortable={true}
              dataIndex="gatewayCode"
              cell={this.renderGatewayDesc}
            />
            <Table.Column
              width={180}
              title="指标组"
              dataIndex="metricGroups"
              cell={this.renderMetricGroup}
            />
            <Table.Column
              width={40}
              title="周期"
              dataIndex="executionCycle"
              cell={this.renderExecutionCycle}
            />
            <Table.Column
              width={80}
              title="状态"
              dataIndex="disabled"
              cell={this.renderStatus}
              sortable={true} />
          </Table>
        </div>

      ActionBar =
        <div style={styles.formItem}>
          <Button onClick={this.onSelectConfirm.bind(this)} disabled={this.state.rowSelection.selectedRows.length == 0} size="small" type="secondary">
            <Icon type="select" />选好了
          </Button>
        </div>
    } else {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
          >
            <Table.Column width={160} title="名称" dataIndex="name" sortable={true} cell={this.renderName} />
            <Table.Column width={120} title="编码" dataIndex="code" />
            <Table.Column
              width={160}
              title="网关"
              sortable={true}
              dataIndex="gatewayCode"
              cell={this.renderGatewayDesc}
            />
            <Table.Column
              width={180}
              title="指标组"
              dataIndex="metricGroups"
              cell={this.renderMetricGroup}
            />
            <Table.Column
              width={160}
              title="扩展配置"
              sortable={true}
              dataIndex="config"
              cell={this.renderConfig}
            />
            <Table.Column
              width={40}
              title="周期"
              dataIndex="executionCycle"
              cell={this.renderExecutionCycle}
            />
            <Table.Column
              width={80}
              title="状态"
              dataIndex="disabled"
              cell={this.renderStatus}
              sortable={true} />
            <Table.Column
              width={80}
              title="操作"
              cell={this.renderOper}
            />
          </Table>
        </div>
      ActionBar =
        <div style={styles.formItem}>
          <form method="get" action={ApiOfResourceTemplate}>
            <Button type="secondary" size="small" style={styles.submitButton} htmlType="submit">
              <Icon type="download" />下载模版
            </Button>
          </form>
          <div>
            <Upload
              action={ApiOfResourceImport}
              beforeUpload={this.beforeUpload}
              onSuccess={this.onSuccess}
              onError={this.onError}
              multiple
              accept='.xlsx'
            >
              <Button type="secondary" size="small" style={styles.submitButton} style={{ 'marginLeft': '10px' }}>
                <Icon type="upload" />导入模版
              </Button>
            </Upload>
          </div>
          <div>
            <Button onClick={this.exportData.bind(this)} type="secondary" size="small" style={{ 'marginLeft': '10px' }}><Icon type="download" />导出数据</Button>
          </div>
          <Button onClick={() => this.onOpenDetailDialog()} size="small" type="secondary" style={{ 'marginLeft': '10px' }}><Icon type="add" />新建</Button>
        </div>
    }
    return (
      <IceContainer style={this.props.styles.container}>
        <Loading visible={this.state.loading} fullScreen shape="fusion-reactor">

          <TableFilter
            filter={this.props.filter}
            forSelectUsage={this.props.forSelectUsage}
            match={this.props.match}
          />
          <Row wrap gutter="20" style={styles.formRow}>
            <Col l="8">
              {ActionBar}
            </Col>
            <Col l="16">
              <Pagination
                style={{ 'marginBottom': '10px', ...this.props.styles.pagination }}
                shape="arrow-only"
                pageSizeSelector="filter"
                current={this.props.page}
                total={instances.pageable.totalElements}
                totalRender={total => `总数: ${total}`}
                pageSize={instances.pageable.size}
                onChange={this.props.handlePaginationChange}
                onPageSizeChange={this.props.handlePageSizeChange}
              />
            </Col>
          </Row>
          {DisplayTable}
          <Pagination
            style={this.props.styles.pagination}
            shape="arrow-only"
            pageSizeSelector="filter"
            current={this.props.page}
            total={instances.pageable.totalElements}
            totalRender={total => `总数: ${total}`}
            pageSize={instances.pageable.size}
            onChange={this.props.handlePaginationChange}
            onPageSizeChange={this.props.handlePageSizeChange}
          />
        </Loading>
        <Dialog
          style={{ width: '50%' }}
          title="修改设备信息"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
};